package com.lmm.lcbusiness.lcbusiness.pages.comweb;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.lcbusiness.lcbusiness.AppBaseActivity;
import com.lmm.lcbusiness.lcbusiness.R;

import butterknife.ButterKnife;


/**
 * Created by gxm on 2017/9/3.
 * 通用容器页面
 */
@Route(path = "/app/webview")
public class CommonWebViewActivity extends AppBaseActivity {

    @Autowired(name = "weburl")
    public String curWebUrl = "";
    @Autowired(name = "enableswipe")
    public boolean enableSwipe = false;


    WebView webView;

    SwipeRefreshLayout swipe;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        setContentView(R.layout.activity_commonwebview);
        ButterKnife.bind(this);

        webView = findViewById(R.id.webview);
        swipe = findViewById(R.id.swipe);

        swipe.setEnabled(enableSwipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadPage();
            }
        });
        initWebViewSetting();
        setupWebViewClient();
        setWebChromeClient();
        setJSInterface();
        loadPage();
    }

    public void loadPage() {
        LogUtils.write(curWebUrl);
        webView.loadUrl(curWebUrl);
    }


    private void initWebViewSetting() {
        WebSettings mWebSettings = webView.getSettings();
        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDefaultTextEncodingName("utf-8");

        String ua = mWebSettings.getUserAgentString();
        mWebSettings.setUserAgentString(ua += ";TH5App");

        //图片加载
        if (Build.VERSION.SDK_INT >= 19) {
            mWebSettings.setLoadsImagesAutomatically(true);
        } else {
            mWebSettings.setLoadsImagesAutomatically(false);
        }

        //JS
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setDomStorageEnabled(true);
    }

    boolean isError = false;

    public void setupWebViewClient() {
        // 重新WebView加载URL的方法
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, final String url) {
                Uri uri = Uri.parse(url);
                ARouter.getInstance().build(uri).navigation(CommonWebViewActivity.this, new NavigationCallback() {
                    @Override
                    public void onFound(Postcard postcard) {
                    }

                    @Override
                    public void onLost(Postcard postcard) {
                        ARouter.getInstance().build("/app/webview")
                                .withString("weburl", url)
                                .navigation();
                    }

                    @Override
                    public void onArrival(Postcard postcard) {

                    }

                    @Override
                    public void onInterrupt(Postcard postcard) {

                    }
                });
                return true;
            }

            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                isError = true;
                webviewError();
            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
                isError = true;
                webviewError();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                if (isFirst) {
//                    if (showThemeLoadingDialog != null && !showThemeLoadingDialog.isShowing()) {
//                        showThemeLoadingDialog.show();
//                    }
//                }
                isError = false;

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }

                if (isError) {
                    webviewError();
                } else {
                    weviewNormal();
                }

//                isFirst = false;
//                mhandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        swipeRefreshLayout.setRefreshing(false);
//                        showThemeLoadingDialog.HideDialog();
//                        showDefaultLoadingDialog.HideDialog();
//                    }
//                }, 1000);
            }
        });
    }

    public void setWebChromeClient() {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(webView, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setActionBarTitle(title);
            }


            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                new AlertDialog.Builder(CommonWebViewActivity.this)
                        .setTitle("提示")
                        .setMessage(message)
                        .setPositiveButton("ok",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialoginterface, int i) {
                                        //按钮事件
                                        //Toast.makeText(AllQuestionActivity.this, "确定",Toast.LENGTH_LONG).show();
                                    }
                                }).show();
                result.confirm();//如果不加这句，线程就会卡死，alert只会劫持一次，以后再也不会劫持
                return true;
            }
        });
    }

    public NaviMethodsUtils methods;

    public void setJSInterface() {
        methods = new NaviMethodsUtils(this, this);
        methods.initWebBridge(webView);
        methods.addComMethod();
    }

    private void webviewError() {

    }

    private void weviewNormal() {

    }
}
